﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetMicro.Cache;
using NetMicro.EventBus.Extensions;
using NetMicro.EventBus.Messages;
using NetMicro.EventBus.Persistences;

namespace NetMicro.EventBus.Policies
{
    public class EventRetryPolicy : IEventRetryPolicy
    {
        public EventRetryPolicy(
            IMessageSerializer messageSerializer,
            ILogger<EventRetryPolicy> logger,
            IOptions<EventBusOptions> options,
            IRetryMessageStorage retryMessageStorage)
        {
            MessageSerializer = messageSerializer;
            Logger = logger;
            Options = options;
            RetryMessageStorage = retryMessageStorage;
        }

        private IMessageSerializer MessageSerializer { get; }
        private ILogger<EventRetryPolicy> Logger { get; }
        private IOptions<EventBusOptions> Options { get; }
        private IRetryMessageStorage RetryMessageStorage { get; }

        public async Task OnRetryAsync(MessageTransfer message, CancellationToken cancellationToken)
        {
            try
            {
                TimeSpan? timespan = message.GetRetry(0);
                if (timespan == null)
                    return;
                MessageStorageTransfer messageStorage = MessageSerializer.ConvertMessageStorageTransfer(message, timespan ?? TimeSpan.Zero);
                await RetryMessageStorage.SaveAsync(messageStorage);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"[EventBus] message listening occur error.");
            }
        }
    }
}
